package com.ihr360.payroll.controller.payrollconfig;

import com.ihr360.authority.sharing.annonation.RestControl;
import com.ihr360.authority.sharing.privilege.AccessControlMethod;
import com.ihr360.commons.entity.AuthUserInfo;
import com.ihr360.commons.exception.Ihr360Exception;
import com.ihr360.commons.request.Ihr360SearchBody;
import com.ihr360.commons.utils.RestToReturnUtils;
import com.ihr360.maven.plugin.ModuleCodeStore;
import com.ihr360.maven.plugin.annotation.FunctionDefinition;
import com.ihr360.maven.plugin.annotation.ModuleDefinition;
import com.ihr360.payroll.model.dto.salary.meta.PayrollConfig;
import com.ihr360.payroll.service.payroll.PayrollConfigService;
import com.ihr360.rest.service.SimpleRestService;
import com.ihr360.rest.webmvc.AbstractRestSimpleWithLongIdController;
import com.ihr360.validation.ValidationUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.domain.Page;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 薪资配置 admin
 *
 * @author tomtao
 */

@Api(value = "薪资任务相关接口")
@RestController
@RequestMapping("/payrollConfigs/admin")
@ModuleDefinition(mainModuleCode = ModuleCodeStore.Module.SALARY_CODE_ADMIN,
        mainModuleName = ModuleCodeStore.Module.SALARY_NAME_ADMIN,
        subModuleCode = ModuleCodeStore.Module.SalaryAdmin.SALARY_SETTING_CODE,
        subModuleName = ModuleCodeStore.Module.SalaryAdmin.SALARY_SETTING_NAME,
        hasExtendsAbstractRestController = true)
@RestControl(controls = {
        AccessControlMethod.METHODS.batchDelete,
        AccessControlMethod.METHODS.deleteOne,
        AccessControlMethod.METHODS.create,
        AccessControlMethod.METHODS.getAll,
        AccessControlMethod.METHODS.getAllInCompany,
        AccessControlMethod.METHODS.update})
public class PayrollConfigAdminController extends AbstractRestSimpleWithLongIdController<PayrollConfig> {

    private static final Logger logger = LoggerFactory.getLogger(PayrollConfigAdminController.class);

    @Autowired
    private PayrollConfigService payrollConfigService;

    @Override
    public SimpleRestService<PayrollConfig, Long> getSimpleRestService() {
        return payrollConfigService;
    }

    @FunctionDefinition(functionName = "删除", functionCode = ModuleCodeStore.Function.PAYROLL_CONFIG)
    @DeleteMapping(value = "/delete/{id}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public boolean deleteByIdA(@PathVariable Long id) {
        if (payrollConfigService.isReferenced(id, false)) {
            ValidationUtils.reject("", "被引用不能删除！");
        }
        try {
            return payrollConfigService.deleteSystemTemplateById(id);
        } catch (Ihr360Exception e) {
            throw e;
        } catch (DataIntegrityViolationException e) {
            logger.warn(e.getMessage(), e);
            throw new Ihr360Exception(null, "要删除的数据已被其他数据关联，无法删除");
        } catch (Exception e) {
            logger.warn(e.getMessage(), e);
            throw new Ihr360Exception(null, "无法删除数据，请刷新后重试");
        }
    }


    @FunctionDefinition(functionName = "获取一个薪资表", functionCode = ModuleCodeStore.Function.PAYROLL_CONFIG)
    @ApiOperation(value = "获取一个薪资表")
    @Override
    public ResponseEntity get(@PathVariable(name = "id") Long id,
                              @RequestParam(name = "projection", required = false) String projection) {
        PayrollConfig payrollConfig = payrollConfigService.getOneSystemTemplate(id);
        return toResource(payrollConfig, projection);
    }

    @FunctionDefinition(functionName = "保存薪资表", functionCode = ModuleCodeStore.Function.PAYROLL_CONFIG)
    @ApiOperation(value = "保存薪资表")
    @PutMapping(value = "/save")
    public void save(@RequestBody PayrollConfig entity, AuthUserInfo userInfo) {
        if (payrollConfigService.isDuplicateNameSystemTemplate(entity.getName(), entity.getId())) {
            ValidationUtils.reject("", "名称不能重复！");
        }
        entity.setCompanyId(userInfo.getCompanyId());
        payrollConfigService.saveOrUpdateSystemTemplate(entity);
        RestToReturnUtils.setMessage("保存成功！");
    }


    @FunctionDefinition(functionName = "用户查询薪资表", functionCode = ModuleCodeStore.Function.PAYROLL_CONFIG)
    @ApiOperation(value = "用户查询薪资表")
    @Override
    public ResponseEntity executeSearch(@RequestBody Ihr360SearchBody<PayrollConfig> searchBody,
                                        @RequestParam(name = "projection", required = false) String projection) {
        Page<PayrollConfig> page = payrollConfigService.searchSystemTemplate(searchBody);
        return toResource(page, projection);
    }

}